package com.obrempon.credit.market.ui.fragment

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.obrempon.credit.market.R
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponRepayListFragmentBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.HttpFragment
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.activity.ObremponOrderPayStatusAct
import com.obrempon.credit.market.ui.adapter.ObremponRepayListApt
import com.obrempon.credit.market.utils.ObremponDensityUtil
import com.obrempon.credit.market.utils.decoration.LinearSpacingItemDecoration
import com.obrempon.credit.market.utils.helper.ObremponProductHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：待还款列表
 */
class ObremponOrderRepayListFragment: HttpFragment() {
    lateinit var binding: ObremponRepayListFragmentBinding
    private var repayAdapter: ObremponRepayListApt? = null
    override fun getObremponRootView(inflater: LayoutInflater): View {
        binding = ObremponRepayListFragmentBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponTextTitleVisibility(View.GONE)
        setObremponBackBtnVisibility(View.INVISIBLE)
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_ff0569ff))
        initOrderRepayRefrashView()
        initOrderRepayRecyclerView()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_REPAY_LIST_START)
    }

    override fun initObremponListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Repay Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,"Repay Page")
        }
    }

    override fun takeObremponData() {
        val repayList = ObremponProductHelper.takeObremponRepayProductList()
        if (repayList.size == 0){
            repayAdapter?.clear()
            val emptyItem = JSONObject()
            emptyItem.put("itemType","emptyItemView")
            repayAdapter?.addFirstItem(emptyItem)
            return
        }
        repayAdapter?.clear()
        repayAdapter?.data = repayList
        showObremponLoading()
        loadObremponRepayInfoAction(0)
    }

    /* 初始化刷新 */
    private fun initOrderRepayRefrashView() {
        binding.repayRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.repayRefreshLayout.setOnRefreshListener {
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESH))
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderRepayRecyclerView(){
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.repayListView.layoutManager = layoutManager
        val decoration = ObremponDensityUtil.dp2px(16f)
        binding.repayListView.addItemDecoration(LinearSpacingItemDecoration(decoration,decoration,decoration,decoration))
        repayAdapter = ObremponRepayListApt(binding.repayListView)
        binding.repayListView.adapter = repayAdapter!!
        binding.repayListView.itemAnimator = DefaultItemAnimator()
        repayAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = repayAdapter!!.getItem(position)
            when(childView.id){
                R.id.buttonRepay -> {//还款
                    val pName = item.optString("product")
                    val pToken = item.optString("token")
                    onObremponPayAction(pName,pToken)
                    addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_REPAY,pName)
                }
                R.id.textEmpty -> {//去申请
                    publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SHOW_HOME))
                }
            }
        }
    }

    /**
     * 链接还款
     */
    private fun showObremponPayLink(linkUrl: String){
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * pin还款
     */
    private fun showObremponPayStatusAction(pName: String, pToken: String, thirdOrderId: String){
        ObremponOrderPayStatusAct.start(requireContext(),pName,pToken,thirdOrderId)
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        when(event.eventType){
            ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESHED -> {
                takeObremponData()
            }
            ObremponEventData.TYPE.OBREMPON_PRODUCT_FINISHED -> {
                hideObremponLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    private fun onObremponPayAction(pName: String,pToken: String){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("product",pName)
            put("token",pToken)
            put("mobile",ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_MOBILE))
            put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_REPAYMENT_MARKET_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideObremponLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    var linkUrl = obj.optString("url","")
                    if (linkUrl.isEmpty()){
                        linkUrl = obj.optString("repayUrl","")
                    }
                    //没有还款链接 - 需要进入还款状态页查询还款状态
                    if (linkUrl.isEmpty()){
                        val thirdOrderId = obj.optString("thirdOrderId")
                        showObremponPayStatusAction(pName,pToken,thirdOrderId)
                    } else {
                        showObremponPayLink(linkUrl)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 获取还款信息
     */
    private fun loadObremponRepayInfoAction(loadIndex: Int){
        if (repayAdapter == null || loadIndex >= repayAdapter!!.itemCount){
            hideObremponLoading()
            return
        }
        val item = repayAdapter!!.getItem(loadIndex)
        val pName = item.optString("product")
        val pToken = item.optString("token")
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_REPAYMENT_INFO_PATH)
            put("product",pName)
            put("token",pToken)
            put("oldFlag","YES")
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    item.put("repayInfo",obj)
                    repayAdapter?.notifyItemChanged(loadIndex)
                    loadObremponRepayInfoAction(loadIndex + 1)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun hideObremponLoading() {
        super.hideObremponLoading()
        binding.repayRefreshLayout.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_REPAY_LIST_END)
    }
}